<template>
  <a-modal
    :open="visible"
    title="成本卡管理"
    :width="1200"
    :mask-closable="true"
    :keyboard="true"
    :closable="false"
  >
    <div class="cost-card-content">
      <!-- 顶部操作栏 -->
      <div class="cost-card-header">
        <a-button type="primary" @click="openAddIngredientDialog" :loading="addIngredientLoading">
          添加成分
        </a-button>
      </div>
      <!-- 成本卡列表 -->
      <vxe-grid
        ref="costCardGrid"
        resizable
        show-overflow
        highlight-hover-row
        keep-source
        row-id="id"
        :columns="costCardTableColumn"
        :loading="costCardLoading"
        height="450"
        :data="selectedIngredients"
      >
        <!-- 操作列 -->
        <template #action_default="{ row, rowIndex }">
          <a-button
            type="link"
            size="small"
            @click="openAddReplacementDialog(rowIndex, row.ingredientProductId)"
          >
            新增替换品
          </a-button>
          <a-button type="link" danger size="small" @click="deleteIngredient(rowIndex)">
            删除
          </a-button>
        </template>

        <template #ingredientUnit_default="{ row }">
          <unit-selector v-model:value="row.unitId" />
        </template>

        <!-- 消耗数量 列自定义内容 -->
        <template #consumeQuantity_default="{ row, rowIndex }">
          <a-input-number
            v-model:value="row.consumeQuantity"
            :precision="0"
            :min="0"
            style="width: 100%"
            placeholder="请输入消耗数量"
            @change="updateConsumeQuantity(rowIndex, $event)"
          />
        </template>

        <!-- 替换品 列自定义内容 -->
        <template #replacements_default="{ row, rowIndex }">
          <div style="padding-left: 15px; padding-right: 15px; padding-bottom: 15px">
            <vxe-grid
              ref="replacementGrid"
              resizable
              show-overflow
              highlight-hover-row
              keep-source
              row-id="id"
              height="auto"
              :data="row.replacements"
              :columns="[
                { type: 'seq', width: 60 },
                { title: '替换品', width: 200, slots: { default: 'replacementName_default' } },
                { field: 'ingredientCategoryName', title: '原料分类', width: 120 },
                {
                  field: 'ingredientUnit',
                  title: '消耗单位',
                  width: 120,
                  slots: { default: 'replacementUnit_default' },
                },
                { title: '消耗数量', minWidth: 120, slots: { default: 'consumeQuantity_default' } },
                {
                  title: '操作',
                  width: 170,
                  fixed: 'right',
                  slots: { default: 'replacements_action_default' },
                },
              ]"
              :toolbar-config="{
                zoom: false,
                custom: false,
                refresh: false,
                slots: {
                  buttons: 'toolbar_buttons',
                },
              }"
            >
              <template #replacementName_default="{ row }">
                {{ `${row.ingredientProductName}` }}
              </template>

              <template #replacementUnit_default="{ row }">
                <unit-selector v-model:value="row.unitId" />
              </template>

              <template #consumeQuantity_default="cel">
                <a-input-number
                  v-model:value="cel.row.consumeQuantity"
                  :precision="0"
                  style="width: 100%"
                  placeholder="消耗数量"
                />
              </template>

              <template #replacements_action_default="cel">
                <a-button
                  type="link"
                  danger
                  size="small"
                  @click="deleteReplacements(row.replacements, cel.rowIndex)"
                >
                  删除
                </a-button>
              </template>
            </vxe-grid>
          </div>
        </template>
      </vxe-grid>
    </div>

    <!-- 添加成分窗口 -->
    <a-modal
      v-model:open="addIngredientVisible"
      title="添加成分"
      :width="1200"
      @ok="confirmSelectIngredients"
      @cancel="handleAddIngredientCancel"
    >
      <div class="add-ingredient-content">
        <!-- 查询表单 -->
        <j-border style="margin-bottom: 16px">
          <j-form bordered @collapse="$refs.addIngredientGrid.refreshColumn()">
            <j-form-item label="编号">
              <a-input v-model:value="addIngredientSearchForm.code" allow-clear />
            </j-form-item>
            <j-form-item label="名称">
              <a-input v-model:value="addIngredientSearchForm.name" allow-clear />
            </j-form-item>
            <j-form-item label="简称">
              <a-input v-model:value="addIngredientSearchForm.shortName" allow-clear />
            </j-form-item>
            <j-form-item label="SKU编号">
              <a-input v-model:value="addIngredientSearchForm.skuCode" allow-clear />
            </j-form-item>
            <j-form-item label="分类">
              <product-category-selector v-model:value="addIngredientSearchForm.categoryId" />
            </j-form-item>
            <j-form-item label="品牌">
              <product-brand-selector v-model:value="addIngredientSearchForm.brandId" />
            </j-form-item>
            <j-form-item label="商品类型">
              <a-select
                v-model:value="addIngredientSearchForm.productType"
                placeholder="全部"
                allow-clear
              >
                <a-select-option
                  v-for="item in $enums.PRODUCT_TYPE.values()"
                  :key="item.code"
                  :value="item.code"
                  >{{ item.desc }}</a-select-option
                >
              </a-select>
            </j-form-item>
            <j-form-item label="创建日期" :content-nest="false">
              <div class="date-range-container">
                <a-date-picker
                  v-model:value="addIngredientSearchForm.startTime"
                  placeholder=""
                  value-format="YYYY-MM-DD 00:00:00"
                />
                <span class="date-split">至</span>
                <a-date-picker
                  v-model:value="addIngredientSearchForm.endTime"
                  placeholder=""
                  value-format="YYYY-MM-DD 23:59:59"
                />
              </div>
            </j-form-item>
            <j-form-item label="状态">
              <a-select
                v-model:value="addIngredientSearchForm.available"
                placeholder="全部"
                allow-clear
              >
                <a-select-option
                  v-for="item in $enums.AVAILABLE.values()"
                  :key="item.code"
                  :value="item.code"
                  >{{ item.desc }}</a-select-option
                >
              </a-select>
            </j-form-item>
          </j-form>
        </j-border>

        <!-- 成分选择列表 -->
        <vxe-grid
          id="AddIngredientGrid"
          ref="addIngredientGrid"
          resizable
          show-overflow
          highlight-hover-row
          keep-source
          row-id="id"
          :proxy-config="addIngredientProxyConfig"
          :columns="addIngredientTableColumn"
          :toolbar-config="addIngredientToolbarConfig"
          :custom-config="{}"
          :pager-config="{}"
          :loading="addIngredientLoading"
          height="400"
          :checkbox-config="{
            checkMethod: checkIngredientMethod,
          }"
        >
          <!-- 工具栏 -->
          <template #toolbar_buttons>
            <a-space>
              <a-button type="primary" @click="searchAddIngredient">查询</a-button>
            </a-space>
          </template>

          <template #unit_default="{ row }">
            <unit-selector v-model:value="row.unit" readOnly />
          </template>
        </vxe-grid>
      </div>
    </a-modal>

    <!-- 替换品选择窗口 -->
    <a-modal
      v-model:open="addReplacementVisible"
      title="选择替换品"
      :width="1200"
      @ok="confirmSelectReplacements"
      @cancel="handleAddReplacementCancel"
    >
      <div class="add-ingredient-content">
        <j-border style="margin-bottom: 16px">
          <j-form bordered @collapse="$refs.addReplacementGrid.refreshColumn()">
            <j-form-item label="编号">
              <a-input v-model:value="addReplacementSearchForm.code" allow-clear />
            </j-form-item>
            <j-form-item label="名称">
              <a-input v-model:value="addReplacementSearchForm.name" allow-clear />
            </j-form-item>
            <j-form-item label="简称">
              <a-input v-model:value="addReplacementSearchForm.shortName" allow-clear />
            </j-form-item>
            <j-form-item label="SKU编号">
              <a-input v-model:value="addReplacementSearchForm.skuCode" allow-clear />
            </j-form-item>
            <j-form-item label="分类">
              <product-category-selector v-model:value="addReplacementSearchForm.categoryId" />
            </j-form-item>
            <j-form-item label="品牌">
              <product-brand-selector v-model:value="addReplacementSearchForm.brandId" />
            </j-form-item>
            <j-form-item label="商品类型">
              <a-select
                v-model:value="addReplacementSearchForm.productType"
                placeholder="全部"
                allow-clear
              >
                <a-select-option
                  v-for="item in $enums.PRODUCT_TYPE.values()"
                  :key="item.code"
                  :value="item.code"
                  >{{ item.desc }}</a-select-option
                >
              </a-select>
            </j-form-item>
            <j-form-item label="创建日期" :content-nest="false">
              <div class="date-range-container">
                <a-date-picker
                  v-model:value="addReplacementSearchForm.startTime"
                  placeholder=""
                  value-format="YYYY-MM-DD 00:00:00"
                />
                <span class="date-split">至</span>
                <a-date-picker
                  v-model:value="addReplacementSearchForm.endTime"
                  placeholder=""
                  value-format="YYYY-MM-DD 23:59:59"
                />
              </div>
            </j-form-item>
            <j-form-item label="状态">
              <a-select
                v-model:value="addReplacementSearchForm.available"
                placeholder="全部"
                allow-clear
              >
                <a-select-option
                  v-for="item in $enums.AVAILABLE.values()"
                  :key="item.code"
                  :value="item.code"
                  >{{ item.desc }}</a-select-option
                >
              </a-select>
            </j-form-item>
          </j-form>
        </j-border>
        <vxe-grid
          id="AddReplacementGrid"
          ref="addReplacementGrid"
          resizable
          show-overflow
          highlight-hover-row
          keep-source
          row-id="id"
          :proxy-config="addReplacementProxyConfig"
          :columns="addReplacementTableColumn"
          :toolbar-config="addIngredientToolbarConfig"
          :custom-config="{}"
          :pager-config="{}"
          :loading="addReplacementLoading"
          height="400"
          :radio-config="{ labelField: 'id', checkMethod: checkReplacementMethod, strict: true }"
        >
          <template #toolbar_buttons>
            <a-space>
              <a-button type="primary" @click="searchAddReplacement">查询</a-button>
            </a-space>
          </template>

          <template #unit_default="{ row }">
            <unit-selector v-model:value="row.unit" readOnly />
          </template>
        </vxe-grid>
      </div>
    </a-modal>

    <!-- 对话框底部按钮 -->
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleConfirm" :loading="confirmLoading"> 确定 </a-button>
    </template>
  </a-modal>
</template>

<script>
  import { defineComponent } from 'vue';
  import { CloseOutlined } from '@ant-design/icons-vue';
  import * as api from '@/api/base-data/product/info';
  import UnitSelector from '@/components/Selector/src/UnitSelector.vue';

  export default defineComponent({
    name: 'CostCardDialog',
    components: {
      UnitSelector,
      CloseOutlined,
    },
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      productId: {
        type: String,
        default: '',
      },
    },
    emits: ['update:visible'],
    data() {
      return {
        costCardLoading: false,
        addIngredientVisible: false,
        addIngredientLoading: false,
        confirmLoading: false, // 确定按钮加载状态
        // 成本卡数据
        costCardData: null,
        // 选中的成分列表
        selectedIngredients: [],
        addIngredientSearchForm: {
          code: '',
          name: '',
          shortName: '',
          skuCode: '',
          categoryId: '',
          brandId: '',
          productType: '',
          startTime: '',
          endTime: '',
          available: '',
        },
        // 替换品相关
        addReplacementVisible: false,
        addReplacementLoading: false,
        addReplacementSearchForm: {
          code: '',
          name: '',
          shortName: '',
          skuCode: '',
          categoryId: '',
          brandId: '',
          productType: '',
          startTime: '',
          endTime: '',
          available: '',
        },
        currentIngredientIndex: null, // 当前操作的成分行index
      };
    },
    computed: {
      // 成本卡列表数据配置
      costCardTableColumn() {
        return [
          {
            title: '替代品',
            type: 'expand',
            width: 100,
            slots: { content: 'replacements_default' },
          },
          { field: 'ingredientProductName', title: '原料名称', width: 160, sortable: true },
          { field: 'ingredientCategoryName', title: '原料分类', width: 120 },
          {
            field: 'ingredientUnit',
            title: '消耗单位',
            width: 120,
            slots: { default: 'ingredientUnit_default' },
          },
          {
            field: 'consumeQuantity',
            title: '消耗数量',
            minWidth: 100,
            slots: { default: 'consumeQuantity_default' },
          },

          { title: '操作', width: 170, fixed: 'right', slots: { default: 'action_default' } },
        ];
      },
      // 添加成分列表数据配置
      addIngredientTableColumn() {
        return [
          { type: 'checkbox', width: 45 },
          { field: 'name', title: '商品名称', minWidth: 160, sortable: true },
          { field: 'categoryName', title: '分类', width: 120 },
          { field: 'unit', title: '单位', width: 80, slots: { default: 'unit_default' } },
        ];
      },
      // 替换品弹窗专用列（有radio）
      addReplacementTableColumn() {
        return [
          { type: 'radio', width: 45 },
          { field: 'name', title: '商品名称', minWidth: 160, sortable: true },
          { field: 'categoryName', title: '分类', width: 120 },
          { field: 'unit', title: '单位', width: 80, slots: { default: 'unit_default' } },
        ];
      },
      // 添加成分请求接口配置
      addIngredientProxyConfig() {
        return {
          props: {
            result: 'datas',
            total: 'totalCount',
          },
          ajax: {
            query: ({ page, sorts }) => {
              return api.query(this.buildAddIngredientQueryParams(page, sorts));
            },
          },
        };
      },
      // 添加成分工具栏配置
      addIngredientToolbarConfig() {
        return {
          // 自定义左侧工具栏
          slots: {
            buttons: 'toolbar_buttons',
          },
        };
      },
      addReplacementProxyConfig() {
        return {
          props: {
            result: 'datas',
            total: 'totalCount',
          },
          ajax: {
            query: ({ page, sorts }) => {
              return api.query(this.buildAddReplacementQueryParams(page, sorts));
            },
          },
        };
      },
    },
    watch: {
      visible: {
        handler(newVal) {
          if (newVal && this.productId) {
            this.loadCostCardData();
          }
        },
        immediate: true,
      },
    },
    methods: {
      // 加载成本卡数据
      async loadCostCardData() {
        if (!this.productId) {
          return;
        }

        this.costCardLoading = true;
        try {
          const result = await api.getCostCard(this.productId);
          this.costCardData = result;
          if (result && result.details) {
            this.selectedIngredients = result.details.map((detail) => ({
              id: detail.id,
              ingredientProductName: detail.ingredientProductName,
              ingredientCategoryName: detail.ingredientCategoryName,
              ingredientUnit: detail.ingredientUnit,
              unitId: detail.unitId,
              consumeQuantity: detail.consumeQuantity,
              ingredientProductId: detail.ingredientProductId,
              replacements: detail.replacements,
            }));
          } else {
            this.selectedIngredients = [];
          }
        } catch (error) {
          console.error('加载成本卡数据失败:', error);
          this.$message.error('加载成本卡数据失败');
          this.selectedIngredients = [];
        } finally {
          this.costCardLoading = false;
          // 强制更新表格
          this.$nextTick(() => {
            if (this.$refs.costCardGrid) {
              console.log('表格数据已更新');
            }
          });
        }
      },
      // 打开添加成分对话框
      openAddIngredientDialog() {
        this.addIngredientVisible = true;
        // 重置查询条件
        this.addIngredientSearchForm = {
          code: '',
          name: '',
          shortName: '',
          skuCode: '',
          categoryId: '',
          brandId: '',
          productType: '',
          startTime: '',
          endTime: '',
          available: '',
        };
        this.$nextTick(() => {
          this.$refs.addIngredientGrid.commitProxy('reload');
        });
      },
      // 添加成分确认
      confirmSelectIngredients() {
        const selectedRecords = this.$refs.addIngredientGrid.getCheckboxRecords();
        if (selectedRecords.length === 0) {
          // 如果没有选择成分，直接关闭对话框
          this.addIngredientVisible = false;
          return;
        }

        const duplicateIngredients = [];
        selectedRecords.forEach((item) => {
          const isDuplicate = this.selectedIngredients.some(
            (existing) => existing.ingredientProductId === item.id,
          );
          if (isDuplicate) {
            duplicateIngredients.push(item.name);
          }
        });

        if (duplicateIngredients.length > 0) {
          this.$message.warning(`以下成分已存在，不能重复添加：${duplicateIngredients.join(', ')}`);
          return;
        }

        selectedRecords.forEach((item) => {
          const ingredient = {
            id: item.id,
            ingredientProductName: item.name,
            ingredientCategoryName: item.categoryName,
            ingredientUnit: item.unit,
            consumeQuantity: 1,
            ingredientProductId: item.id,
          };
          this.selectedIngredients.push(ingredient);
        });

        this.$message.success(`已添加 ${selectedRecords.length} 个成分`);
        this.addIngredientVisible = false;
      },
      // 添加成分取消
      handleAddIngredientCancel() {
        this.addIngredientVisible = false;
      },
      // 更新消耗数量
      updateConsumeQuantity(index, value) {
        if (this.selectedIngredients[index]) {
          this.selectedIngredients[index].consumeQuantity = value;
        }
      },
      // 删除单个成分
      deleteIngredient(index) {
        if (this.selectedIngredients[index]) {
          const ingredient = this.selectedIngredients[index];
          this.$confirm({
            title: '确认删除',
            content: `确定要删除成分"${ingredient.ingredientProductName}"吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              this.selectedIngredients.splice(index, 1);
              this.$message.success('成分删除成功');
            },
            onCancel: () => {
              // 用户取消删除
            },
          });
        }
      },
      // 检查成分是否可选
      checkIngredientMethod({ row }) {
        return !this.selectedIngredients.some(
          (existing) => existing.ingredientProductId === row.id,
        );
      },
      // 确定按钮处理
      async handleConfirm() {
        // 验证数据
        if (this.selectedIngredients.length === 0) {
          this.$message.warning('请至少添加一个成分');
          return;
        }

        // 验证消耗数量
        const invalidItems = this.selectedIngredients.filter(
          (item) => !item.consumeQuantity || item.consumeQuantity <= 0,
        );
        if (invalidItems.length > 0) {
          this.$message.warning('请为所有成分设置有效的消耗数量');
          return;
        }
        // 验证替换品消耗数量
        for (const item of this.selectedIngredients) {
          if (item.replacements && item.replacements.length) {
            const invalidReps = item.replacements.filter(
              (rep) => !rep.consumeQuantity || rep.consumeQuantity <= 0,
            );
            if (invalidReps.length > 0) {
              this.$message.warning('请为所有替换品设置有效的消耗数量');
              return;
            }
          }
        }

        this.confirmLoading = true;
        try {
          // 构造details，带上replacements字段
          // 后端需支持：每个明细的replacements为数组，内容为{ingredientProductId, consumeQuantity}
          const details = this.selectedIngredients.map((item) => ({
            id: item.id,
            sourceProductId: item.sourceProductId,
            ingredientProductId: item.ingredientProductId,
            unitId: item.unitId,
            consumeQuantity: item.consumeQuantity,
            replacements: (item.replacements || []).map((rep) => ({
              ingredientProductId: rep.ingredientProductId,
              consumeQuantity: rep.consumeQuantity,
              unitId: rep.unitId,
            })),
          }));

          if (this.costCardData) {
            // 更新成本卡
            const updateVo = {
              id: this.costCardData.id,
              productId: this.productId,
              name: this.costCardData.name,
              description: this.costCardData.description,
              available: this.costCardData.available,
              details,
            };
            await api.updateCostCard(updateVo);
            this.$message.success('成本卡更新成功');
          } else {
            // 创建成本卡
            const createVo = {
              productId: this.productId,
              name: '成本卡',
              description: '',
              available: true,
              details,
            };
            await api.createCostCard(createVo);
            this.$message.success('成本卡创建成功');
          }
          this.$emit('update:visible', false);
        } catch (error) {
          console.error('保存成本卡失败:', error);
          this.$message.error('保存成本卡失败');
        } finally {
          this.confirmLoading = false;
        }
      },
      // 关闭成本卡对话框
      handleCancel() {
        console.log('handleCancel被调用');
        this.$emit('update:visible', false);
        // 清空数据
        this.costCardData = null;
        this.selectedIngredients = [];
      },
      // 处理关闭按钮点击
      handleCloseClick() {
        console.log('handleCloseClick被调用');
        this.handleCancel();
      },
      // 构建添加成分查询参数
      buildAddIngredientQueryParams(page, sorts) {
        return {
          pageIndex: page.currentPage,
          pageSize: page.pageSize,
          sorts: sorts,
          code: this.addIngredientSearchForm.code,
          name: this.addIngredientSearchForm.name,
          shortName: this.addIngredientSearchForm.shortName,
          skuCode: this.addIngredientSearchForm.skuCode,
          categoryId: this.addIngredientSearchForm.categoryId,
          brandId: this.addIngredientSearchForm.brandId,
          productType: this.addIngredientSearchForm.productType,
          startTime: this.addIngredientSearchForm.startTime,
          endTime: this.addIngredientSearchForm.endTime,
          available: this.addIngredientSearchForm.available,
        };
      },
      // 搜索添加成分
      searchAddIngredient() {
        this.$refs.addIngredientGrid.commitProxy('reload');
      },
      // 打开新增替换品弹窗
      openAddReplacementDialog(rowIndex, sourceProductId) {
        this.currentIngredientIndex = rowIndex;
        this.addReplacementVisible = true;
        this.addReplacementSearchForm = {
          sourceProductId: sourceProductId,
          code: '',
          name: '',
          shortName: '',
          skuCode: '',
          categoryId: '',
          brandId: '',
          productType: '',
          startTime: '',
          endTime: '',
          available: '',
        };
        this.$nextTick(() => {
          if (this.$refs.addReplacementGrid) {
            this.$refs.addReplacementGrid.commitProxy('reload');
            this.$refs.addReplacementGrid.clearRadioRow();
          }
        });
      },
      // 确认选择替换品
      confirmSelectReplacements() {
        const selectedRecord = this.$refs.addReplacementGrid.getRadioRecord();
        if (!selectedRecord) {
          this.addReplacementVisible = false;
          return;
        }
        const ingredient = this.selectedIngredients[this.currentIngredientIndex];
        if (!ingredient.replacements) ingredient.replacements = [];
        // 不允许选择自己
        if (String(ingredient.ingredientProductId) === String(selectedRecord.id)) {
          this.$message.error('不能选择自己作为替换品');
          return;
        }
        // 不允许重复
        if (
          ingredient.replacements.some(
            (r) => String(r.ingredientProductId) === String(selectedRecord.id),
          )
        ) {
          this.$message.warning('该替换品已存在');
          return;
        }
        ingredient.replacements.push({
          id: selectedRecord.id,
          sourceProductId: this.addReplacementSearchForm.sourceProductId,
          ingredientProductName: selectedRecord.name,
          ingredientCategoryName: selectedRecord.categoryName,
          ingredientUnit: selectedRecord.unit,
          ingredientProductId: selectedRecord.id,
          consumeQuantity: 1,
        });
        this.$message.success('已添加 1 个替换品');
        this.addReplacementVisible = false;
      },
      // 取消选择替换品
      handleAddReplacementCancel() {
        this.addReplacementVisible = false;
        this.addReplacementSearchForm = {
          code: '',
          name: '',
          shortName: '',
          skuCode: '',
          categoryId: '',
          brandId: '',
          productType: '',
          startTime: '',
          endTime: '',
          available: '',
        };
        this.$nextTick(() => {
          if (this.$refs.addReplacementGrid) {
            this.$refs.addReplacementGrid.clearRadioRow();
          }
        });
      },
      // 替换品查询参数
      buildAddReplacementQueryParams(page, sorts) {
        return {
          pageIndex: page.currentPage,
          pageSize: page.pageSize,
          sorts: sorts,
          code: this.addReplacementSearchForm.code,
          name: this.addReplacementSearchForm.name,
          shortName: this.addReplacementSearchForm.shortName,
          skuCode: this.addReplacementSearchForm.skuCode,
          categoryId: this.addReplacementSearchForm.categoryId,
          brandId: this.addReplacementSearchForm.brandId,
          productType: this.addReplacementSearchForm.productType,
          startTime: this.addReplacementSearchForm.startTime,
          endTime: this.addReplacementSearchForm.endTime,
          available: this.addReplacementSearchForm.available,
        };
      },
      // 替换品表格查询
      searchAddReplacement() {
        this.$refs.addReplacementGrid.commitProxy('reload');
      },
      // 检查替换品是否可选
      checkReplacementMethod({ row }) {
        const ingredient = this.selectedIngredients[this.currentIngredientIndex];
        if (!ingredient) return false;
        // 禁止选择自己，确保类型一致
        if (String(ingredient.ingredientProductId) === String(row.id)) return false;
        // 禁止重复
        if (
          ingredient.replacements &&
          ingredient.replacements.some((r) => String(r.ingredientProductId) === String(row.id))
        )
          return false;
        return true;
      },
      // 删除替换品
      deleteReplacements(data, index) {
        if (data[index]) {
          this.$confirm({
            title: '确认删除',
            content: `确定要删除"${data[index].ingredientProductName}"吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              data.splice(index, 1);
              this.$message.success('删除成功');
            },
            onCancel: () => {
              // 用户取消删除
            },
          });
        }
      },
    },
  });
</script>

<style scoped>
  .cost-card-content {
    padding: 0;
  }

  .cost-card-header {
    margin-bottom: 10px;
  }

  .add-ingredient-content {
    padding: 0;
  }

  .date-range-container {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .date-split {
    color: #666;
    font-size: 12px;
  }
</style>
